package pt.iscte.daam.ejb;

import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceContextType;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

import pt.iscte.daam.json.PedidoJson;
import pt.iscte.daam.model.Imovel;
import pt.iscte.daam.model.Quarto;
import pt.iscte.daam.queries.Queries;
import pt.iscte.daam.servicos.Servicos;

@Stateless
@LocalBean
@Path("/quarto")
public class ServicoQuarto {
	@PersistenceContext(unitName = "CustomerService", type = PersistenceContextType.TRANSACTION)
	EntityManager entityManager;
	
	@POST
	@Path(Servicos.listaEcraPrincipal)
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Quarto[] getListaEcraPrincipal(PedidoJson pedido) {
		TypedQuery<Quarto> query = entityManager.createNamedQuery(Queries.SELECT_QUARTOS, Quarto.class);
		query.setFirstResult(pedido.getNumeroQuartos() * pedido.getNumeroPagina());
		query.setMaxResults(pedido.getNumeroQuartos());
		List<Quarto> resultado = query.getResultList();
				
		return resultado.toArray(new Quarto[0]);
	}
	
	@POST
	@Path(Servicos.detalheQuarto)
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Quarto[] getDetalheQuarto(PedidoJson pedido) {
		TypedQuery<Quarto> query = entityManager.createNamedQuery(Queries.SELECT_QUARTO_POR_ID, Quarto.class);
		query.setParameter("id", pedido.getIdQuarto()).getSingleResult();
		List<Quarto> resultado = query.getResultList();
		
		if(resultado.isEmpty()){
			return null;
		}
		
		return resultado.toArray(new Quarto[0]);
	}
	
	@POST
	@Transactional
	@Path(Servicos.inserirQuarto)
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public Quarto inserirImovel(Quarto quarto) {
		Imovel imovel = entityManager.find(Imovel.class, quarto.getImovel().getId());
		
		quarto.setImovel(imovel);
		
		entityManager.persist(quarto);
		
		return quarto;
	}
}
